﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;

public partial class Manager_OrderDetail_SignOrderPD : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(Manager_OrderDetail_SignOrderPD));
        if (!IsPostBack)
        {
            if (Session["AdminUserID"] == null)
            {
                Response.Write("<script language=javascript>alert('Time is out.');window.open('../Default.aspx','_top');</script>");
                return;
            }

            if (Session["IsAdmin"] != "S")
            {
                clsGetMenuAuth clsAuth = new clsGetMenuAuth(Session["AdminUserID"].ToString(), Session["AutID"].ToString(), Session["IsAdmin"].ToString(), Request.QueryString["CodeID"]);
                if (clsAuth.IsSignAuth() == false)
                    pnlControl.Visible = false;
            }
            BindData();
            VisibleButton();

        }
    }


    protected DataSet GetStoreList()
    {
        clsWebShop cls = new clsWebShop();
        DataSet ds = cls.Get_StoreByKindNoNoneProc();
        return ds;

    }

    private DropDownList BindStoreList(DropDownList ddlStore)
    {
        clsWebShop cls = new clsWebShop();
        ListItem item = new ListItem();
        ddlStore.DataSource = cls.Get_StoreByKindNoNoneProc().Tables[0];
        ddlStore.DataTextField = "StName";
        ddlStore.DataValueField = "StID";
        ddlStore.DataBind();
        item.Text = "Tất cả";
        item.Value = "0";
        ddlStore.Items.Insert(0, item);
        ddlStore.SelectedItem.Selected = false;
        return ddlStore;

    }
    private void VisibleButton()
    {
        string State = Request.QueryString["State"];
        if (State == "Y")
        {
            lblTitle.Text = "ĐƠN ĐANG XÁC NHẬN";
            btnOk.Visible = false;
            btnCancel.Visible = true;
            btnSending.Visible = true;
            btnSend.Visible = false;
            chkPayment.Visible = true;
            tdNote.Visible = true;
        

        }
        else if (State == "S")
        {
            lblTitle.Text = "ĐƠN ĐANG GIAO HÀNG";
            btnOk.Visible = false;
            btnCancel.Visible = true;
            btnSending.Visible = false;
            btnSend.Visible = true;
            grvMaster.Columns[7].Visible = false;
            chkPayment.Visible = true;
            tdNote.Visible = true;
            txtNote.ReadOnly = true;
     

        }
        else if (State == "C")
        {
            lblTitle.Text = "ĐƠN ĐÃ HỦY";
            btnOk.Visible = true;
            btnCancel.Visible = false;
            btnSend.Visible = false;
            btnSending.Visible = false;
            grvMaster.Columns[4].Visible = false;
            grvMaster.Columns[7].Visible = false;
            tdNote.Visible = true;

           
            tblPaymoney.Attributes.CssStyle.Add("display", "none");
       
        }
        else if (State == "E")
        {
            lblTitle.Text = "ĐƠN ĐÃ GIAO HÀNG";
            btnOk.Visible = false;
            btnCancel.Visible = false;
            btnSend.Visible = false;
            grvMaster.Columns[4].Visible = false;
            grvMaster.Columns[5].Visible = false;
            grvMaster.Columns[7].Visible = false;     
            btnSending.Visible = false;
            tdNote.Visible = true;
            txtNote.ReadOnly = true;
            txtNote.BackColor = System.Drawing.Color.FromName("AliceBlue");
            tblPaymoney.Attributes.CssStyle.Add("display", "none");
            
            /*for (int i = 0; i < grvMaster.Rows.Count; i++)
            {
                CheckBox chkApprove = (CheckBox)grvMaster.Rows[i].FindControl("chkApprove");
               // chkApprove.Visible = false;
            }*/
        }
        else
        {
            lblTitle.Text = "ĐƠN CHỜ XÁC NHẬN";
            btnOk.Visible = true;
            btnCancel.Visible = true;
            btnSend.Visible = false;
            btnSending.Visible = false;
            grvMaster.Columns[4].Visible = false;
            grvMaster.Columns[5].Visible = false;
            grvMaster.Columns[7].Visible = false;
            grvMaster.Columns[9].Visible = false;
            td1.Visible = false;
            td2.Visible = false;
            td3.Visible = false;
            td4.Visible = false;
            tdNote.Visible = false;
            tblPaymoney.Attributes.CssStyle.Add("display", "none");

 
        }

        if (txtRemainPrice.Text == "" || txtRemainPrice.Text == "0" && (lblTongsotien.Text==txtRepaid.Text))
        {
            tblPaymoney.Attributes.CssStyle.Add("display", "none");
            chkPayment.Visible = false;
        }

    }
    private void BindData()
    {
        clsWebShop cls = new clsWebShop();
        clsCommon clsCom = new clsCommon();
        //Lay so luong trong kho
        //Session["dtCountStore"] = cls.Get_QuantityStoreGroup("", "0").Tables[0];
        DataTable dt;
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("StartDate", "");
        msg.CreateFirstNode("EndDate", "");
        msg.CreateFirstNode("Status", Request.QueryString["State"]);
        msg.CreateFirstNode("End_MK", "");
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        dt = cls.Get_OrderPDByCondition(msg.GetXmlStr.ToString()).Tables[0];


        if (dt.Rows.Count > 0)
        {
            lblMaDH.Text = dt.Rows[0]["OrderID"].ToString();
            lblTenKH.Text = dt.Rows[0]["CusNm"].ToString();
            // lblTaxNo.Text = clsCom.FormatDate(dt.Rows[0]["BirthDay"].ToString());
            lblDiaChi.Text = dt.Rows[0]["Address"].ToString();
            lblNoichon.Text = dt.Rows[0]["PlaceNm"].ToString();
            lblSDT.Text = dt.Rows[0]["Phone"].ToString();
            lblEmail.Text = dt.Rows[0]["Email"].ToString();
            lblTaxNo.Text = dt.Rows[0]["TaxNo"].ToString();
            if (lblTaxNo.Text.Trim() == "")
            {
                trTaxNo.Visible = false;
            }

            lblQuantity.Text = FormatMoney(dt.Rows[0]["SumQuantity"].ToString());
            lblTongsotien.Text = FormatMoney(dt.Rows[0]["SumTotal"].ToString());


            lblUSD.Text = "<b>Tỉ giá USD:</b> " + FormatMoney(dt.Rows[0]["USD"].ToString()) + " VNĐ";
            hidRate.Value = dt.Rows[0]["USD"].ToString();
            txtNote.Text = dt.Rows[0]["Note"].ToString();            
            if (dt.Rows[0]["Note_Cus"].ToString().Trim() != "")
            {
                lblNoteCus.Text = dt.Rows[0]["Note_Cus"].ToString();
            }
            if (Request.QueryString["State"] == "S" || Request.QueryString["State"] == "Y")
            {                
                txtRemainPrice.Text = FormatMoney(dt.Rows[0]["RemainPrice"].ToString());
                txtRepaid.Text = FormatMoney(dt.Rows[0]["Repaid"].ToString());
                hidRemainPrice.Value = dt.Rows[0]["RemainPrice"].ToString();
                hidRepaid.Value = dt.Rows[0]["Repaid"].ToString();
            }
            else if (Request.QueryString["State"] == "E")
            {
                txtRepaid.Text = FormatMoney(dt.Rows[0]["SumTotal"].ToString());
                txtRemainPrice.Text = "0";
            }
            else
            {
                txtRemainPrice.Text = FormatMoney(dt.Rows[0]["SumTotal"].ToString());
                txtRepaid.Text = "0";
            }
           

            grvMaster.DataSource = dt;
            grvMaster.DataBind();
  
            /*for (int i = 0; i < grvMaster.Rows.Count; i++)
            {
                TotalQuantity += decimal.Parse(grvMaster.Rows[i].Cells[3].Text.ToString());
                TextBox lblTotal = (TextBox)grvMaster.Rows[i].FindControl("lblTotal");
                TotalPrice += decimal.Parse(lblTotal.Text);
            }*/

        
        }
    }
    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
    public string GetQuantityStore(string PDID, string StID)
    {
        clsWebShop cls = new clsWebShop();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("PdID", PDID);
        msg.CreateFirstNode("StID", StID);
        DataTable dt = cls.Get_QuantityStoreByCondition(msg.GetXmlStr).Tables[0];
        if (dt.Rows.Count > 0)
            return dt.Rows[0][0].ToString();
        return "0";

    }

    protected void grvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string End_MK = DataBinder.Eval(e.Row.DataItem, "End_MK").ToString();
            string U_Status = DataBinder.Eval(e.Row.DataItem, "U_Status").ToString();
            if (End_MK == "D") //Don & KH dang o trang thai xoa
            {
                e.Row.Cells[1].BackColor = System.Drawing.Color.Red;
            }
            if (U_Status == "D")
            {
                AutoNumber1.BgColor = "red";
            }
            Label lblQuantityStore = (Label)e.Row.FindControl("lblQuantityStore");
            DropDownList ddlStore = (DropDownList)e.Row.FindControl("ddlStore");
            Label lblDonGia = (Label)e.Row.FindControl("lblDonGia");
            TextBox lblTotal = (TextBox)e.Row.FindControl("lblTotal");
            if (DataBinder.Eval(e.Row.DataItem, "KindNo").ToString() == "P")
            {
                string sQ_Store = "0";
                clsWebShop cls = new clsWebShop();  
                if (Request.QueryString["State"] == "S")
                {
                    string StID = DataBinder.Eval(e.Row.DataItem, "StID").ToString();
                    if (StID != "" && StID != "0")
                        ddlStore.Items.FindByValue(StID).Selected = true;
                    /*if (DataBinder.Eval(e.Row.DataItem, "RemainPrice").ToString() == "0" || DataBinder.Eval(e.Row.DataItem, "RemainPrice").ToString() == "")
                    {
                        e.Row.Cells[8].Text = "Trả đủ tiền";
                    }*/
                }

                if (Request.QueryString["State"] != "N" && Request.QueryString["State"] != "E")
                {
                    DataTable dt = cls.Get_QuantityStoreGroup(DataBinder.Eval(e.Row.DataItem, "PDID").ToString(), ddlStore.SelectedValue).Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        sQ_Store = dt.Rows[0]["Quantity_Store"].ToString();
                    }
                    lblQuantityStore.Text = sQ_Store;
                    if (Request.QueryString["State"] == "Y" || Request.QueryString["State"] == "S")
                    {
                        ddlStore.Visible = true;
                        if (int.Parse(lblQuantityStore.Text) < int.Parse(e.Row.Cells[3].Text))
                            e.Row.Cells[5].BackColor = System.Drawing.Color.Orange;                        
                        
                    }
                    else
                    {
                        if (int.Parse(lblQuantityStore.Text) < int.Parse(e.Row.Cells[3].Text))
                            e.Row.Cells[5].BackColor = System.Drawing.Color.Orange;
                    }
                }
                
                lblDonGia.Text = FormatMoney(lblDonGia.Text);
                lblTotal.Text = FormatMoney(lblTotal.Text);

            }
            else
            {
                ddlStore.Visible = false;
                e.Row.Cells[5].BackColor = System.Drawing.Color.LightYellow;
                e.Row.Cells[7].Text = "";
                e.Row.Cells[8].Text = "";
                lblQuantityStore.Text = "Free";
            }
            if (Request.QueryString["State"] == "S" || Request.QueryString["State"] == "E")
            {
                TextBox txtNoteDetail = (TextBox)e.Row.FindControl("txtNoteDetail");
                txtNoteDetail.ReadOnly = true;
                txtNoteDetail.BorderStyle = BorderStyle.None;
            }
            
           

        }
    }
    protected void ddlStore_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindData();
    }

    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
    public string AjaxUpdateOrderState(string State, string sOrder)
    {
        clsWebShop cls = new clsWebShop();
        string myMsg = "";
        switch (State.ToLower())
        {
            case "save":
                cls.UpdateData("update OrderPD set Status='Y' where  OrderID='" + sOrder + "'");
                myMsg = "Y";
                break;
            case "cancel":
                cls.UpdateData("update OrderPD set Status='N' where  OrderID='" + sOrder + "'");
                myMsg = "N";
                break;
        }
        return myMsg;
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        Response.Redirect("OrderDetail.aspx?CodeID=" + Request.QueryString["CodeID"] + "&sDate=" + Request["sDate"].ToString() + "&eDate=" + Request["eDate"].ToString() + "&sDrop=" + Request["sDrop"].ToString() + "");

    }
    private string FormatMoney(decimal dNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", dNum);
        }
        catch (Exception) { }
        return sReturn;
    }

    private string FormatMoney(string sNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", decimal.Parse(sNum));
        }
        catch (Exception) { }
        return sReturn;
    }
    //Dang cho duyet
    protected void btnOk_Click(object sender, EventArgs e)
    {
        clsWebShop cls = new clsWebShop();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
        string xml = cls.Upd_WaitingSignOrderPD(msg.GetXmlStr);
        msg = new PccMsg(xml);
        string strOutput = msg.Query("strOutput");
        if (strOutput == "-2")
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Trong đơn đặt hàng " + Request.QueryString["OrderID"] + ". Sản phẩm trong kho không đủ số lượng')</script>");
            BindData();
            return;
        }
        else
        {
            //INSERT FLOWORDERHIST
            clsFunAp clsFun = new clsFunAp();

           string Note=clsFun.NoteTo_Y(txtRepaid.Text.Replace(",", ""), txtRemainPrice.Text.Replace(",", ""), " VNĐ");
            if(Request.QueryString["State"]=="C")
                Note=clsFun.NoteTo_Recover();

            msg = new PccMsg();
            msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
            msg.CreateFirstNode("SignUser", Session["AdminUserID"].ToString());
            msg.CreateFirstNode("Status", "Y");
            msg.CreateFirstNode("Note", Note);
            cls.Ins_Upd_FlowOrderHist(msg.GetXmlStr);           

            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Xác nhận thành công');  window.location.href='" + strReturnPage() + "';</script>");

        }
    }

    //KET THUC DON
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (txtRemainPrice.Text.Trim() != "" && txtRemainPrice.Text.Trim() != "0" && chkPayment.Checked==false)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Chưa thanh toán đủ số tiền còn thiếu');</script>");
            return;
        }
        clsCommon clsCom = new clsCommon();
        //Update Trang Thai OrderPD= E
        clsWebShop cls = new clsWebShop();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        msg.CreateFirstNode("Repaid", clsCom.ConvertToDecimal(txtRepaid.Text.Replace(",", "")).ToString());
        msg.CreateFirstNode("RemainPrice", clsCom.ConvertToDecimal(txtRemainPrice.Text.Replace(",", "")).ToString());
        msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
        string xml = cls.Upd_EndOrderPD(msg.GetXmlStr);
        msg = new PccMsg(xml);
        string strOutput = msg.Query("strOutput");
        if (strOutput == "0")
        {
            for (int i = 0; i < grvMaster.Rows.Count; i++)
            {
                Label lblKindNo = (Label)grvMaster.Rows[i].FindControl("lblKindNo");
                string PDID = grvMaster.Rows[i].Cells[1].Text.Trim();
               
                DropDownList ddlStore = (DropDownList)grvMaster.Rows[i].FindControl("ddlStore");
                string StID = "";
                if (lblKindNo.Text == "P")
                    StID = ddlStore.SelectedValue;


                msg = new PccMsg();
                msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
                msg.CreateFirstNode("PDID", PDID);
                msg.CreateFirstNode("StID", clsCom.ConvertToDecimal(StID).ToString());    
                msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
                string strXml = cls.Upd_EndOrder_Store(msg.GetXmlStr);
                PccMsg errmsg = new PccMsg(strXml);
                string strOutput1 = errmsg.Query("strOutput");
                if (strOutput1 != "0")//Undo
                {
                    UndoEndOrder();
                    cls.UpdateData("Update OrderPD set Status='S' where  OrderID='" + Request.QueryString["OrderID"] + "'   Update OrderDetail SET StID=NULL  Where OrderID='" + Request.QueryString["OrderID"] + "'     Delete Store_Product Where OrderID='" + Request.QueryString["OrderID"] + "'");
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Có lỗi xác nhận đơn. Xin liên hệ với nhà quản trị')</script>");
                    return;
                }

            }

            //INSERT FLOWORDERHIST
            clsFunAp clsFun = new clsFunAp();

            msg = new PccMsg();
            msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
            msg.CreateFirstNode("SignUser", Session["AdminUserID"].ToString());
            msg.CreateFirstNode("Status", "E");
            msg.CreateFirstNode("Note", clsFun.NoteTo_E(lblTongsotien.Text.Replace(",", ""), " VNĐ"));
            cls.Ins_Upd_FlowOrderHist(msg.GetXmlStr);

            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Xác nhận thành công');  window.location.href='" + strReturnPage() + "';</script>");


            SendMailBasket(Request.QueryString["OrderID"]);
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Giao hàng thành công');  window.location.href='" + strReturnPage() + "';</script>");

        }
        else//Undo
        {
            cls.UpdateData("Update OrderPD set Status='Y' where  OrderID='" + Request.QueryString["OrderID"] + "'");
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Có lỗi xác nhận đơn. Xin liên hệ với nhà quản trị')</script>");

        }
    }

    private void SendMailBasket(string OrderID)
    {
        string HTML = "", result = "";
        int SL = 0;
        decimal TT = 0;
        if (grvMaster.Rows.Count > 0)
        {
            HTML += " <table border='0' bordercolor='#407db3' cellpadding='2' cellspacing='0' style='border-collapse: collapse;'   width='100%'>";
            HTML += "             <tr>";
            HTML += "                 <td align='center' colspan='4'>";
            HTML += "                      <table border='0' cellpadding='0' cellspacing='0' style='width: 100%'>";
            HTML += "    <tr>";
            HTML += " <td rowspan='5' style='width: 76px'>";
            HTML += " <img src='" + System.Configuration.ConfigurationManager.AppSettings["AppAddress"] + "/Images/Banner/logo.png' /></td>";
            HTML += " <td align='left'>";
            HTML += " &nbsp;<span id='Label11'  style='ont-family:Tahoma; font-size:13px'>Công ty TNHH Hoàng Nguyên Bảo</span>";
            HTML += " </td>";
            HTML += " </tr>";
            HTML += " <tr>";
            HTML += " <td align='left'>";
            HTML += " &nbsp;<span id='Label18' style='ont-family:Tahoma; font-size:13px'>MST: 0309543650</span></td>";
            HTML += " </tr>";
            HTML += " <tr>";
            HTML += " <td align='left'>";
            HTML += " &nbsp;<span id='Label12' style='ont-family:Tahoma; font-size:13px'>16/83 Nguyễn Thiện Thuật P2 Q3</span></td>";
            HTML += " </tr>";
            HTML += " <tr>";
            HTML += " <td align='left'>";
            HTML += " &nbsp;<span id='Label16' style='ont-family:Tahoma; font-size:13px'>Tel: (08)62909078-62909079 Cel:098.2600917</span></td>";
            HTML += " </tr>";
            HTML += " </table>";
            HTML += " </td>";
            HTML += " </tr>";
            HTML += " <tr>";
            HTML += " <td colspan='4' align='center' valign='top' style='height: 31px'>";
            HTML += " <span id='Label2' style='font-family: Tahoma; font-size: 13pt; font-weight: bold;'>";
            HTML += " CHI TIẾT ĐƠN ĐẶT HÀNG</span></td>";
            HTML += " </tr>";
            HTML += " <tr>";
            HTML += " <td align='right' colspan='4' valign='bottom'>";
            HTML += " <table border='0' cellpadding='0' cellspacing='0'>";
            HTML += " <tr>";
            HTML += " <td align='left'>";
            HTML += " Mã đơn hàng</td>";
            HTML += " <td align='left' valign='middle' style='white-space: nowrap'>";
            HTML += " :&nbsp;<span id='lblMaDH' style='font-weight: bold;'>" + OrderID + "</span></td>";
            HTML += " </tr>";
            HTML += " </table>";
            HTML += " </td>";
            HTML += " </tr>";
            HTML += " <tr>";
            HTML += " <td colspan='4'>";
            HTML += " <div style='border-style:dotted; border-width:1px;'>";
            HTML += " <table id='AutoNumber1' style='border-right: 1px solid; padding-right: 0px; border-top: 1px solid; padding-left: 0px; padding-bottom: 0px; border-left: 1px solid; padding-top: 1px; border-bottom: 1px solid; border-collapse: collapse'    bordercolor='#111111' cellspacing='0'                cellpadding='2' width='100%'>";
            HTML += " <tr>";
            HTML += " <td  nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px;   border-bottom: 1px dotted; width: 110px;' align='left' nowrap>";
            HTML += " Tên khách hàng</td>";
            HTML += " <td align='left' colspan='3' nowrap='nowrap' style='padding-right: 4px; padding-left: 4px;     padding-bottom: 1px; padding-top: 1px; border-bottom: 1px dotted'>";
            HTML += " :&nbsp;<span id='lblTenKH'>" + lblTenKH.Text + "</span></td>";
            HTML += " </tr>";
            HTML += " <tr>";
            HTML += " <td nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px; border-bottom: 1px dotted; width: 95px;' align='left'>";
            HTML += " Địa chỉ</td>";
            HTML += " <td nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px; border-bottom: 1px dotted' align='left'>";
            HTML += " :&nbsp;<span id='lblDiaChi'>" + lblDiaChi.Text + "</span></td>";
            HTML += " <td nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px;         border-bottom: 1px dotted; width: 114px;' align='left'>";
            HTML += " Tỉnh, Thành Phố</td>";
            HTML += " <td nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px;   border-bottom: 1px dotted' align='left'>";
            HTML += " :&nbsp;<span id='lblNoichon'>" + lblNoichon.Text + "</span></td>";
            HTML += " </tr>";
            if (lblTaxNo.Text.Trim() != "")
            {
                HTML += " <tr>";
                HTML += " <td nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px;   border-bottom: 1px dotted; width: 95px;' align='left'>";
                HTML += " Mã số thuế</td>";
                HTML += " <td align='left' colspan='3' nowrap='nowrap' style='padding-right: 4px; padding-left: 4px;     padding-bottom: 1px; padding-top: 1px; border-bottom: 1px dotted'>";
                HTML += " :&nbsp;<span id='lblTenKH'>" + lblTaxNo.Text + "</span></td>";
                HTML += " </tr>";
            }

            HTML += " <tr>";
            HTML += " <td nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px;   width: 95px;' align='left'>";
            HTML += " Điện thoại</td>";
            HTML += " <td nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px;   align='left'>";
            HTML += " :&nbsp;<span id='lblSDT'>" + lblSDT.Text + " </span>";
            HTML += " </td>";
            HTML += " <td nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px;    width: 114px;' align='left'>";
            HTML += " Email</td>";
            HTML += " <td nowrap style='padding-right: 4px; padding-left: 4px; padding-bottom: 2px; padding-top: 2px;    align='left'>";
            HTML += " :&nbsp;<span id='lblEmail'>" + lblEmail.Text + "</span></td>";
            HTML += " </tr>";
            HTML += " </table>";
            HTML += " </td>";
            HTML += " </tr>";
            HTML += "   <tr>";
            HTML += "  <td>";
            HTML += "     </td>";
            HTML += "    <td>";
            HTML += "    </td>";
            HTML += " <td>";
            HTML += "  </td>";
            HTML += "   <td>";
            HTML += "  </td>";
            HTML += "  </tr>";

            HTML += "   </table>";
            HTML += "   </div>";

            //================================================= danh sach san pham
            HTML += " <div width='100%' align='right'>";
            HTML += lblUSD.Text;
            HTML += "<table border='1' cellpadding='3' cellspacing='0' style='width: 100%;border-collapse:collapse' bordercolor='#407db3'>";
            //Header
            HTML += "<tr height='30px' style='BACKGROUND-COLOR: #D8ECFF;font-family:Tahoma;font-size:13px;'>";
            HTML += "<th width='2%' nowrap>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[0].Cells[1])).ContainingField.HeaderText + "</th>"; //Masp
            HTML += "<th align='left'>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[0].Cells[2])).ContainingField.HeaderText + "</th>";  //Ten sp
            HTML += "<th   width='2%' nowrap>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[0].Cells[3])).ContainingField.HeaderText + "</th>"; //So luong
            HTML += "<th   width='10%' nowrap>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[0].Cells[6])).ContainingField.HeaderText + "</th>"; //Don Gia
            HTML += "<th  width='10%' nowrap>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[0].Cells[8])).ContainingField.HeaderText + "</th>";//thanh tien
            HTML += "<th  width=10%' nowrap>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[0].Cells[9])).ContainingField.HeaderText + "</th>"; //ghi chu
            HTML += "</tr>";
            //Row
            for (int i = 0; i < grvMaster.Rows.Count; i++)
            {
                if (i % 2 == 0)
                    HTML += "<tr style='BACKGROUND-COLOR: #feffeb;font-family:Tahoma;font-size:12px;'>";
                else
                    HTML += "<tr style='BACKGROUND-COLOR: #ffffff;font-family:Tahoma;font-size:12px;'>";

               /* Label lblMaSP = (Label)grvMaster.Rows[i].FindControl("lblMaSP");
                Label lblTenSP = (Label)grvMaster.Rows[i].FindControl("lblTenSP");
                Label lblDonGia = (Label)grvMaster.Rows[i].FindControl("lblDonGia");
                Label lblSoLuong = (Label)grvMaster.Rows[i].FindControl("txtSoLuong");
                Label lblThanhTien = (Label)grvMaster.Rows[i].FindControl("lblThanhTien");
                Label lblKindMoney = (Label)grvMaster.Rows[i].FindControl("lblKindMoney");
                Label lblNoteDetail = (Label)grvMaster.Rows[i].FindControl("lblNoteDetail");*/

                string lblMaSP = grvMaster.Rows[i].Cells[1].Text;
                string lblTenSP = grvMaster.Rows[i].Cells[2].Text;
                string lblSoLuong = grvMaster.Rows[i].Cells[3].Text;
                Label lblDonGia = (Label)grvMaster.Rows[i].FindControl("lblDonGia");
                Label lblRate = (Label)grvMaster.Rows[i].FindControl("lblRate");
                TextBox lblTotal = (TextBox)grvMaster.Rows[i].FindControl("lblTotal");
                TextBox txtNoteDetail = (TextBox)grvMaster.Rows[i].FindControl("txtNoteDetail");
                HTML += "<td align='center'  nowrap><a  href='" + System.Configuration.ConfigurationManager.AppSettings["AppAddress"].ToString() + "/Shopping/Stall/ProductDetail.aspx?PDID=" + lblMaSP + "'>" + lblMaSP + "</a></td>";
                HTML += "<td  nowrap>" + lblTenSP + "</td>";
                HTML += "<td align='center'  nowrap>" + lblSoLuong + "</td>";
                HTML += "<td align='right'  nowrap>" + lblDonGia.Text + " " + lblRate.Text + "</td>";
                HTML += "<td align='right'  nowrap>" + lblTotal.Text + "</td>";
                HTML += "<td align='center'  nowrap>" + txtNoteDetail.Text + "</td>";
          

                HTML += "</tr>";
            }
            /*//Footer
            HTML += "<tr height='30px' style='BACKGROUND-COLOR: orange;font-family:Tahoma;font-size:13px;'>";


            Label lblSL = (Label)grvMaster.Rows[grvMaster.Rows.Count - 1].FindControl("lblSL");
            Label lbltt = (Label)grvMaster.Rows[grvMaster.Rows.Count - 1].FindControl("lbltt");
            Label lblVND = (Label)grvMaster.Rows[grvMaster.Rows.Count - 1].FindControl("lblVND");

            HTML += "<th colspan='3' align='left'><b>Tổng cộng</b></th>";
            HTML += "<th align='right'>" + SL.ToString() + "</th>";
            HTML += "<th align='right'><b>$</b> " + FormatMoney(TT).ToString() + "</th>";

            /*HTML += "<td>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[grvMaster.Rows.Count-1].Cells[0])).ContainingField.FooterText + "</td>";
            HTML += "<td>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[grvMaster.Rows.Count - 1].Cells[1])).ContainingField.FooterText + "</td>";
            HTML += "<td>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[grvMaster.Rows.Count - 1].Cells[2])).ContainingField.FooterText + "</td>";
            HTML += "<td>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[grvMaster.Rows.Count - 1].Cells[3])).ContainingField.FooterText + "</td>";
            HTML += "<td>" + ((System.Web.UI.WebControls.DataControlFieldCell)(grvMaster.Rows[grvMaster.Rows.Count - 1].Cells[4])).ContainingField.FooterText + "</td>";
            HTML += "</tr>";*/


            HTML += "</table>";
            HTML += "</div>";
            HTML += "<br>";


            //Footer
            HTML += " <table border='0' bordercolor='#407db3' cellpadding='2' cellspacing='0' style='border-collapse: collapse;'   width='100%'>";
            HTML += "<tr>";
            HTML += "    <td align='center' valign='top'>";
            HTML += "        <table style='border-collapse: collapse;' border='0' bordercolor='#407db3' cellpadding='0' cellspacing='0'>";
            HTML += "            <tbody><tr>";
            HTML += "                <td style='padding-right: 10px; white-space: nowrap;' align='right' valign='bottom'>";
            HTML += "                    <span id='ctl00_ContentPlaceHolder1_Label14' style='font-weight: bold;font-family: tahoma; font-size: 13px;'>Tổng số lượng: </span></td>";
            HTML += "                <td colspan='2' style='border-bottom: thin dotted black; width: 160px; white-space: nowrap;' align='right' valign='bottom'>";
            HTML += "                    <span id='ctl00_ContentPlaceHolder1_lblQuantity' style='font-family: tahoma; font-size: 13px;'>" + lblQuantity.Text + "</span></td>";

         
            HTML += "            </tr>";
            HTML += "            <tr>";
            HTML += "                <td style='padding-right: 10px; white-space: nowrap;' align='right' valign='bottom'>";
            HTML += "                    <span id='ctl00_ContentPlaceHolder1_Label15' style='font-weight: bold;font-family: tahoma; font-size: 13px;'>Tổng số tiền thanh toán: </span></td>";
            HTML += "                <td colspan='2' style='border-bottom: thin dotted black; white-space: nowrap;' align='right' valign='bottom'>";
            HTML += "                    <span id='ctl00_ContentPlaceHolder1_lblTotal' style='font-family: tahoma; font-size: 13px;'>" + lblTongsotien.Text + "</span>";
            HTML += "                    <span id='ctl00_ContentPlaceHolder1_Label6' style='font-family: tahoma; font-size: 13px;'>VNĐ</span>&nbsp;</td>";
            HTML += "";
            HTML += "            </tr>";
            HTML += "        </tbody></table>";
            HTML += "    </td>";
            HTML += "</tr>";
            if (txtNote.Text.Trim() != "")
            {
                HTML += "<tr>";
                HTML += "    <td align='left' valign='top'>";
                HTML += "        <table border='0' cellpadding='0' cellspacing='0'>";
                HTML += "            <tbody><tr>";
                HTML += "               <td style='border-bottom: thin dotted black;'>";
                HTML += "                    <span id='ctl00_ContentPlaceHolder1_lblChuY' style='font-weight: bold;'>Ghi chú: </span>";
                HTML += "                   <span id='ctl00_ContentPlaceHolder1_lblNote'>" + txtNote.Text + "</span></td>";
                HTML += "            </tr>";
                HTML += "        </tbody></table>";
                HTML += "    </td>";
                HTML += "</tr>";
            }
            HTML += "</table>";


            HTML += "<br>";
            HTML += "Thank you to  my website: <a  href='http://" + System.Configuration.ConfigurationManager.AppSettings["AppAddress"].ToString() + "'>" + System.Configuration.ConfigurationManager.AppSettings["AppAddress"].ToString() + "</a>";

            clsCommon clsCom = new clsCommon();
            result = clsCom.Send_AppEmail(System.Configuration.ConfigurationManager.AppSettings["SaleMail"].ToString(), lblEmail.Text, System.Configuration.ConfigurationManager.AppSettings["SaleMail"].ToString() + ";" + System.Configuration.ConfigurationManager.AppSettings["WebMail"].ToString(), "Chi tiet Don Dat hang(" + System.DateTime.Now.ToString("dd/MM/yyyy  hh:mm:ss") + ")", HTML);
        }

    }

    //Dang giao hang
    protected void btnSending_Click(object sender, EventArgs e)
    {      

        //Update Trang Thai OrderPD= S
        clsWebShop cls = new clsWebShop();
        clsCommon clsCom = new clsCommon();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        msg.CreateFirstNode("Repaid",  clsCom.ConvertToDecimal(txtRepaid.Text.Replace(",","")).ToString());
        msg.CreateFirstNode("RemainPrice", clsCom.ConvertToDecimal(txtRemainPrice.Text.Replace(",", "")).ToString());
        msg.CreateFirstNode("Note", txtNote.Text);
        msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
        string xml = cls.Upd_SendOrderPD(msg.GetXmlStr);

        msg = new PccMsg(xml);
        string strOutput = msg.Query("strOutput");
        if (strOutput == "0")
        {
            for (int i = 0; i < grvMaster.Rows.Count; i++)
            {
                Label lblKindNo = (Label)grvMaster.Rows[i].FindControl("lblKindNo");
                string PDID = grvMaster.Rows[i].Cells[1].Text.Trim();
                DropDownList ddlStore = (DropDownList)grvMaster.Rows[i].FindControl("ddlStore");
                string StID = "";
                if (lblKindNo.Text == "P")
                    StID = ddlStore.SelectedValue;

                //Cap nhat gia khuyen mai
                TextBox txtSaleOfPrice = (TextBox)grvMaster.Rows[i].FindControl("txtSaleOfPrice");
                Label lblDonGia = (Label)grvMaster.Rows[i].FindControl("lblDonGia");

                string Price = lblDonGia.Text.Replace(",", "");
                string OldPrice = "0";
                if (txtSaleOfPrice.Text != "" && txtSaleOfPrice.Text != "0")
                {
                    Price = txtSaleOfPrice.Text;
                    OldPrice = lblDonGia.Text.Replace(",", "");
                }

                //Total 
                TextBox lblTotal = (TextBox)grvMaster.Rows[i].FindControl("lblTotal");
                lblTotal.ReadOnly = false;
                string Total = lblTotal.Text.Replace(",", "");

                //NoteDetail
                TextBox txtNoteDetail = (TextBox)grvMaster.Rows[i].FindControl("txtNoteDetail");
                string sNoteDetail = txtNoteDetail.Text;
                
              
      

                msg = new PccMsg();
                msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
                msg.CreateFirstNode("PDID", PDID);
                msg.CreateFirstNode("StId", StID);
                msg.CreateFirstNode("Price", clsCom.ConvertToDecimal(Price.Replace(",", "")).ToString());
                msg.CreateFirstNode("OldPrice", clsCom.ConvertToDecimal(OldPrice.Replace(",", "")).ToString());
                msg.CreateFirstNode("Total", clsCom.ConvertToDecimal(Total.Replace(",", "")).ToString());
                msg.CreateFirstNode("NoteDetail", sNoteDetail);
                msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
                string strXml = cls.Upd_SendOrderDetail(msg.GetXmlStr);

                PccMsg errmsg = new PccMsg(strXml);
                string strOutput1 = errmsg.Query("strOutput");
                if (strOutput1 != "0")//Undo
                {
                    UndoSendingOrder();
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Có lỗi xác nhận đơn. Xin liên hệ với nhà quản trị')</script>");
                    
                    return;
                }

            }
            //INSERT FLOWORDERHIST
            clsFunAp clsFun = new clsFunAp();
            msg = new PccMsg();
            msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
            msg.CreateFirstNode("SignUser", Session["AdminUserID"].ToString());
            msg.CreateFirstNode("Status", "S");
            msg.CreateFirstNode("Note", clsFun.NoteTo_S(txtRepaid.Text.Replace(",", ""), txtRemainPrice.Text.Replace(",", ""), " VNĐ"));

            cls.Ins_Upd_FlowOrderHist(msg.GetXmlStr);

            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Xác nhận đơn giao hàng thành công');  window.location.href='" + strReturnPage() + "';</script>");

        }
        else//Undo
        {
            UndoSendingOrder();
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Có lỗi xác nhận đơn. Xin liên hệ với nhà quản trị')</script>");

        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
       
        clsWebShop cls = new clsWebShop();
        string sOrderID = Request.QueryString["OrderID"];
        /*if (Request.QueryString["State"] == "S")
        {
            cls.UpdateData("Update OrderPD set Status='C',Note='"+txtNote.Text+"',EndDate='" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "'  where  OrderID='" + Request.QueryString["OrderID"] + "'      update OrderDetail 	SET  Total=OldTotal,price= case 	when oldprice = 0 then   price 		else oldprice 	  end  where  OrderID='" + Request.QueryString["OrderID"] + "'");
        }
        else
        {
            cls.UpdateData("update OrderPD set Status='C',Note='" + txtNote.Text + "',EndDate='" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "' where  OrderID='" + sOrderID + "'");
        }*/

        cls.UpdateData("update OrderPD set Repaid='0',  RemainPrice='" + lblTongsotien.Text.Replace(",", "") + "',OldRemainPrice='" + lblTongsotien.Text.Replace(",", "") + "' , Status='C',Note='" + txtNote.Text + "',EndDate='" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "' where  OrderID='" + sOrderID + "'");

        //INSERT FLOWORDERHIST
        clsFunAp clsFun = new clsFunAp();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("OrderID", Request.QueryString["OrderID"]);
        msg.CreateFirstNode("SignUser", Session["AdminUserID"].ToString());
        msg.CreateFirstNode("Status", "C");
        msg.CreateFirstNode("Note", clsFun.NoteTo_C());

        cls.Ins_Upd_FlowOrderHist(msg.GetXmlStr);

        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Hủy bỏ thành công');  window.location.href='" + strReturnPage() + "';</script>");
        //ReturnPage();

    }

    private string strReturnPage()
    {
        return "OrderDetail.aspx?CodeID=" + Request.QueryString["CodeID"] + "&sDate=" + Request.QueryString["sDate"] + "&eDate=" + Request.QueryString["eDate"] + "&sState=" + Request.QueryString["sState"] + "&sOrderID=" + Request.QueryString["sOrderID"] + "&PageIndex=" + Request.QueryString["PageIndex"];
    }

    private void ReturnPage()
    {
        Response.Redirect("OrderDetail.aspx?CodeID=" + Request.QueryString["CodeID"] + "&sDate=" + Request.QueryString["sDate"] + "&eDate=" + Request.QueryString["eDate"] + "&sState=" + Request.QueryString["sState"] + "&sOrderID=" + Request.QueryString["sOrderID"] + "&PageIndex=" + Request.QueryString["PageIndex"]);

    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        ReturnPage();
    }
   

    private void UndoEndOrder()
    {
        clsWebShop cls = new clsWebShop();
       // cls.UpdateData("Update OrderPD set Status='S' where  OrderID='" + Request.QueryString["OrderID"] + "'      update OrderDetail 	SET Repaid=0,RemainPrice=OldTotal,Total=OldTotal,price= case 	when oldprice = 0 then   price 		else oldprice 	  end  where  OrderID='" + Request.QueryString["OrderID"] + "'");
        cls.UpdateData("Update OrderPD set Status='S' where  OrderID='" + Request.QueryString["OrderID"] + "'  Delete Store_Product   Where OrderID='" + Request.QueryString["OrderID"] + "'");

    }

    private void UndoSendingOrder()
    {
        clsWebShop cls = new clsWebShop();
        cls.UpdateData("Update OrderPD set Status='Y' where  OrderID='" + Request.QueryString["OrderID"] + "' ");

    }
}